<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Baqi\Alimns\AliMnsMsg;
use App\Models\RebateOrder;
use App\Models\Report;
use App\Models\SystemBalance;
use App\Models\SystemLog;
use App\Models\Profit;
use App\Models\Lines;
use App\Models\User;
use App\Models\Shop;
use App\Models\Order;
use App\Models\UserServerBalance;
use Illuminate\Support\Facades\DB;

include (base_path('extend/Alimsg/Alimsg.php')); 

class ProfitShare extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'profit:share';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '利润分发';

    private $gx_one_value;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $report_money_product = Report::where('status', 2)->sum('money_product');//获取所有待分发的返利商品利润
        $rebate_sum  = User::where('rebate_points', '>', 0)->where('status', 1)->sum('rebate_points');
        $rebated_sum = User::where('rebated_points', '>', 0)->where('status', 1)->sum('rebated_points');
        
        $temp = 0;

        if($rebate_sum - $rebated_sum > 0){

            $temp = $report_money_product / ($rebate_sum - $rebated_sum);

        }
        
         $smss = new \ Alimsg();

        // $smss = new AliMnsMsg;
        
        //每份贡献获益小于1，进行累积暂停发放
        if($temp < 1){
            //发送短信通知
            // $smss->send_sms('13331128315', '每份贡献获益小于1，进行累积暂停发放', 'reg');
            $smss->sendSms('18595602136', 'reg', '每份贡献获益小于1，进行累积暂停发放');
            die;
        }

        //正常发放流程
        $rebate_list = Report::where('status', 2)->get();//获取所有待分发的列表

        $res = $this->platform($rebate_list);

        if($res){

            // $smss->send_sms('13331128315', date('Y-m-d H:i:s').'脚本执行成功利润分发成功', 'reg');
            $smss->sendSms('18595602136', 'reg', date('Y-m-d H:i:s').'脚本执行成功利润分发成功');

        }else{

            // $smss->send_sms('13331128315', date('Y-m-d H:i:s').'脚本执行成功利润分发失败', 'reg');
            $smss->send_sms('18595602136', 'reg', date('Y-m-d H:i:s').'脚本执行成功利润分发失败');

        }

    }

    /**
     * 利润分发(店铺分发 债权盘分发 平台分发)
     *
     * @return bool
     */
    private function platform($rebate_list)
    {

        //组装利润分发日志
        $sys_log = [];
        // 开启事务
        DB::beginTransaction();

        try{
            
            $pt_money    = 0;//平台总利润
            $fanli_money = 0;//返利总金额

            foreach ($rebate_list as $k => $v) {
                
                $start = date("Y-m-d", $v->audit_date)." 00:00:00";
                $end   = date("Y-m-d", $v->audit_date)." 23:59:59";
                $list  = RebateOrder::where('created_at', '>=', $start)->where('created_at', '<=', $end)->where('is_return', 0)->get();
                
                if($list){
                    
                    //平台某一天应分配的利润和
                    $day_pt_money = 0;

                    foreach ($list as $key => $val) {
                        
                        //增加店铺分润明细
                        $profit = new Profit;
                        $profit->order_sn    = $val->order_sn;
                        $profit->shop_id     = $val->shop_id;
                        $profit->user_id     = $val->user_id;
                        $profit->phone       = User::where('id', $val->user_id)->value('user_mobile');
                        $profit->money       = $val->total_price;
                        $profit->other_money = $val->shop_money;//店铺应得的利润
                        $profit->type        = 1;
                        $profit->superior    = User::where('id', $val->user_id)->value('tg_id');
                        $profit->save();
                        
                        //给店铺增加分润金额
                        $shop = Shop::find($val->shop_id);
                        $shop->money = $shop->money + $val->shop_money;
                        
                        //助推金分发明细
                        $zt = new Profit;
                        $zt->order_sn    = $val->order_sn;
                        $zt->shop_id     = $val->shop_id;
                        $zt->user_id     = $val->user_id;
                        $zt->phone       = User::where('id', $val->user_id)->value('user_mobile');
                        $zt->money       = $val->total_price;
                        $zt->other_money = $val->debt_money;//助推队列的利润
                        $zt->type        = 2;
                        $zt->superior    = $tg_id = User::where('id', $val->user_id)->value('tg_id');
                        $zt->save();
                        //助推金调用队列债权盘接口 开启助推
                        
                        Lines::assist($val->debt_money, $val->shop_id, $tg_id, $val->order_sn);
                        $shop->help_money = $shop->help_money + $val->debt_money;//增加店铺余额 助推金
                        $shop->save();//店铺余额保存

                        //改变订单分润表的分发状态
                        RebateOrder::where('id', $val->id)->update(['is_return'=>1]);

                        //计算平台的应分利润总和
                        $pt_money     += $val->platform_money;
                        //计算平台某一天应分配的利润和
                        $day_pt_money += $val->platform_money;
                        //计算返利盘待返总金额
                        $fanli_money  += $val->rebate_money;

                    }

                }

                $sys_log[$k]['order_sn'] = '';
                $sys_log[$k]['money'] = $day_pt_money;
                $sys_log[$k]['type'] = 1;
                $sys_log[$k]['audit_date'] = $v->audit_date;
                $sys_log[$k]['created_at'] = date('Y-m-d H:i:s');
                $sys_log[$k]['updated_at'] = date('Y-m-d H:i:s');

                //修改审核报表的完成状态
                Report::where('id', $v->id)->update(['status'=>3]);

            }

            //增加平台分润总和
            $system = SystemBalance::find(1);
            $system->share_gold = $system->share_gold + $pt_money;
            $system->save();
            //增加平台分润日志
            SystemLog::insert($sys_log);

            //销毁不使用数据 释放内存
            $list        = null;
            $rebate_list = null;
            $sys_log     = null;
            $k           = null;
            $v           = null;
            $key         = null;
            $val         = null;
            unset($list);unset($rebate_list);unset($sys_log);unset($k);unset($v);unset($key);unset($val);

            //返利盘利润分发流程
            $rebate_sum  = User::where('rebate_points', '>', 0)->where('status', 1)->sum('rebate_points');
            $rebated_sum = User::where('rebated_points', '>', 0)->where('status', 1)->sum('rebated_points');

            $temp =  $fanli_money / ($rebate_sum - $rebated_sum);//每份贡献的值保留两位小数 舍弃后面的值
            $this->gx_one_value = $temp;

            //获取舍弃的值（余数）存储给平台收益
            $duoyu_pingtai = (($fanli_money * 100) % ($rebate_sum - $rebated_sum)) / 100;
            $system->balance = $system->balance + $duoyu_pingtai;
            $system->save();
            //增加返利舍弃的利润增加给平台收入余额log
            SystemLog::create(['order_sn'=>'', 'money'=>$duoyu_pingtai, 'type'=>2]);

            //给用户订单分发返利流程按区块数量1000分发
            User::where('rebate_points', '>', 0)->where('status', 1)->select('id', 'rebate_points', 'rebated_points')->chunk(1000, function ($users) {

                foreach ($users as $user) {
                    //获取有可用贡献
                    $temp_points = $user->rebate_points - $user->rebated_points;

                    if($temp_points > 0){
                        //获取用户应发返利
                        $temp_money = $temp_points * $this->gx_one_value;
                        //分发用户返利
                        $this->user_order_profit($temp_money, $user->id);

                    }

                }

            });

            // 提交事务
            DB::commit();

            return true;

        } catch (\Exception $e) {

            // 回滚事务
            DB::rollback();
            return false;

        }

    }

    /**
     * 递归处理用户订单返利
     *
     * @return bool
     */
    private function user_order_profit($temp_money, $user_id)
    {
        //查询当前用户为返利完成的返利单子
        $first_order = Order::where('user_id', $user_id)->where('is_schedule', 0)->where('is_rebate', 1)->where('status', 3)->orderBy('id', 'asc')->first();
        //正常分发流程
        if($first_order){

            $order_temp_money = $first_order->rebate_amount - $first_order->return_amount;

            if($order_temp_money > 0){

                //返利金额未返满流程
                if($order_temp_money > $temp_money){
                    //增加订单返利金额
                    $first_order->return_amount = $first_order->return_amount + $temp_money;
                    $first_order->save();
                    //给用户增加余额
                    User::where('id', $user_id)->increment('balance', $temp_money);
                    User::where('id', $user_id)->increment('rebated_points', floor($temp_money)/100);

                    UserServerBalance::create(['user_id'=>$user_id, 'order_sn'=>$first_order->order_sn, 'money'=>$temp_money, 'type'=>2, 'action_type'=>2, 'status'=>2]);

                }

                //返利金额正好返满
                if($order_temp_money == $temp_money){

                    //增加订单返利金额
                    $first_order->return_amount = $first_order->return_amount + $temp_money;
                    $first_order->is_schedule = 1;
                    $first_order->save();
                    //给用户增加余额
                    User::where('id', $user_id)->increment('balance', $temp_money);
                    User::where('id', $user_id)->increment('rebated_points', floor($temp_money)/100);

                    UserServerBalance::create(['user_id'=>$user_id, 'order_sn'=>$first_order->order_sn, 'money'=>$temp_money, 'type'=>2, 'action_type'=>2, 'status'=>2]);

                }

                //返利金额溢出
                if($order_temp_money < $temp_money){

                    //获取溢出的金额用于递归
                    $yichu_money = $temp_money - $order_temp_money;

                    //增加订单返利金额
                    $first_order->return_amount = $first_order->return_amount + $order_temp_money;
                    $first_order->is_schedule = 1;
                    $first_order->save();
                    //给用户增加余额
                    User::where('id', $user_id)->increment('balance', $order_temp_money);
                    User::where('id', $user_id)->increment('rebated_points', floor($temp_money)/100);

                    UserServerBalance::create(['user_id'=>$user_id, 'order_sn'=>$first_order->order_sn, 'money'=>$order_temp_money, 'type'=>2, 'action_type'=>2, 'status'=>2]);

                    //递归处理溢出金额
                    $this->user_order_profit($yichu_money, $user_id);

                }

            }else{
                //订单已经返还完成流程 改变订单状态 递归继续执行用户订单返利
                $first_order->is_schedule = 1;
                $res = $first_order->save();

                if($res){

                    $this->user_order_profit($temp_money, $user_id);//递归

                }else{

                    die;//mysql网络问题结束脚本

                }

            }

        }else{

            //该用户没有订单分发 把利润分给平台
            $system = new SystemBalance;
            $system->balance = $system->balance + $temp_money;
            $system->save();
            //增加平台利润log
            SystemLog::create(['order_sn'=>'', 'money'=>$temp_money, 'type'=>3, 'user_id'=>$user_id]);


        }


    }

}
